﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Rubik.Common
{
    public class CubeDumpValidator
    {
        private static void ValidateColorsCount(byte[][,] dump)
        {
            IDictionary<int, int> colorStatistics = new Dictionary<int, int>();

            for (int i = 0; i < 6; i++)
            {
                for (int j = 0; j < Cube.Scale; j++)
                {
                    for (int k = 0; k < Cube.Scale; k++)
                    {
                        int color = dump[i][j, k];
                        int count;
                        if (!colorStatistics.TryGetValue(color, out count))
                        {
                            count = 0;
                        }
                        ++count;
                        colorStatistics[color] = count;
                    }
                }
            }

            foreach (KeyValuePair<int, int> item in colorStatistics)
            {
                int color = item.Key;
                int count = item.Value;
                if (count != 9)
                {
                    throw new ArgumentOutOfRangeException("dump",
                        String.Format("Invalid number of item with color #{0}. Expected 9 but was {1}",
                        color, count));
                }
            }
        }

        private static void ValidateCenteralColors(byte[][,] dump)
        {
            HashSet<int> colors = new HashSet<int>();
            for (int i = 0; i < 6; i++)
            {
                int color = dump[i][1, 1];
                if (colors.Contains(color))
                {
                    throw new ArgumentOutOfRangeException("dump",
                        "Duplicated color in the cental item");
                }
                colors.Add(color);
            }
        }

        public void Validate(byte[][,] dump)
        {
            ValidateColorsCount(dump);
            ValidateCenteralColors(dump);
        }
    }
}
